<template>
  <!-- 轮播图区域 -->
  <div class="container">
    <category-swiper :switch-time="4000"
                     hidden-cate/>
  </div>

  <!-- 分类推荐区域 -->
  <div class="container">
    <!-- 全部分类 -->
    <category-recommend title="全部分类">
      <category-recommend-cate v-for="cate in category.children"
                               :key="cate.id"
                               :data="cate"/>
    </category-recommend>

    <!-- 单独分类 -->
    <category-recommend v-if="category.children && category.children.length"
                        v-for="cate in category.children"
                        :key="cate.id"
                        :title="`- ${cate.name} -`"
                        sub-title="温暖柔软，品质之选">
      <template #top-right>
        <more :href="`/category/sub/${cate.id}`"></more>
      </template>
      <category-recommend-good v-for="good in cate.goods"
                               :data="good"
                               :key="good.id"/>
    </category-recommend>
  </div>
</template>

<script lang="ts"
        setup>
import {getCategory} from '@/api/category'
import CategoryRecommend from '@/components/library/CategoryRecommend.vue'
import CategoryRecommendCate from '@/components/library/CategoryRecommendCate.vue'
import CategoryRecommendGood from '@/components/library/CategoryGood.vue'
import More from '@/components/library/More.vue'
import CategorySwiper from '@/components/library/Swiper.vue'
import {useCommonStore} from '@/stores/common'
import type {Category} from '@/types/category'
import {storeToRefs} from 'pinia'
import {ref, watch} from 'vue'
import {onBeforeRouteLeave, useRoute} from 'vue-router'

let route = useRoute()
let commonStore = useCommonStore()
let {pathList} = storeToRefs(commonStore)

let category = ref<Category>({})

let stopWatch = watch(() => route,() => {
  requestAll()
}, {
  immediate: true,
  deep: true
})

onBeforeRouteLeave(() => {
  stopWatch()
})

// 发起所有接口请求
function requestAll(): void {
  Promise.all([
    getCategory(<string>route.params.id)
  ]).then(([cateRes]) => {
    initCategory(cateRes)
  })
}

// 初始化分类数据
function initCategory(res: any): void {
  category.value = <Category>res.result
  // 设置页面path
  pathList.value = [pathList.value[0], {name: <string>category.value.name ,path: ''}]
}
</script>